/*
 Developer: John Archer (john.archer.jpa@gmail.com)

 This file is part of VTBuilder.

 VTBuilder is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License.

 VTBuilder is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with VTBuilder.  If not, see <http://www.gnu.org/licenses/>.
 */
package core.rb;

import core.rb.r.MR;
import core.sb.SB;
import core.sb.s.Seq;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class MB implements Comparator<MB> {

    public List<MR> mrl;
    public int refLen;

    public MB() {
        this.mrl = new ArrayList<MR>();
    }

    public MB(List<MR> mrl) {
        this.mrl = mrl;
    }

    public void clear() {
        this.mrl.clear();
    }

    public MB subMB(int s, int e) {
        boolean repeat = true;
        int lBand = 0;
        while (repeat && lBand < this.mrl.size()) {
            if (this.mrl.get(lBand++).e >= s) {
                repeat = false;
            }
        }
        repeat = true;
        int uBand = lBand;
        while (repeat && uBand < this.mrl.size()) {
            if (this.mrl.get(uBand++).s >= e) {
                repeat = false;
            }
        }
        List<MR> sublist = this.mrl.subList(lBand, uBand);
        for (int i = 0; i < sublist.size(); i++) {
            sublist.get(i).s = sublist.get(i).s - s;
            sublist.get(i).e = sublist.get(i).e - s;
        }
        return new MB(sublist);
    }

    public SB sb(int s, int e) {
        int sub = e - s;
        SB sb = new SB();
        boolean repeat = true;
        int lBand = 0;
        while (repeat && lBand < this.mrl.size()) {
            if (this.mrl.get(lBand++).e >= s) {
                repeat = false;
            }
        }
        repeat = true;
        int uBand = lBand;
        while (repeat && uBand < this.mrl.size()) {
            if (this.mrl.get(uBand++).s >= e) {
                repeat = false;
            }
        }
        int sCut, eCut;
        for (int r = lBand; r < uBand; r++) {
            if (this.mrl.get(r).s <= s && this.mrl.get(r).e >= e) {
                sCut = s - this.mrl.get(r).s;
                eCut = sCut + sub;
                sb.seqs.add(
                        new Seq(
                        this.mrl.get(r).dna.substring(sCut, eCut),
                        this.mrl.get(r).i));
            }
        }
        return sb;
    }

    @Override
    public int compare(MB t, MB t1) {
        if (t.mrl.size() > t1.mrl.size()) {
            return -1;
        } else if (t.mrl.size() < t1.mrl.size()) {
            return 1;
        }
        return 0;
    }
}